package cn.iocoder.yudao.module.reading.controller.admin.page;

import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.reading.controller.admin.page.vo.*;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.BookPageDO;
import cn.iocoder.yudao.module.reading.service.page.AdminBookPageService;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 管理后台 - 绘本页面管理
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 绘本页面管理")
@RestController
@RequestMapping("/reading/admin/pages")
@Validated
@Slf4j
public class AdminBookPageController {

    @Resource
    private AdminBookPageService adminBookPageService;

    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    /**
     * 检查当前用户是否为管理员
     * 绘本页面管理只允许管理员操作
     */
    private void checkAdminPermission() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(401, "用户未登录");
        }
        if (!UserTypeEnum.ADMIN.getValue().equals(loginUser.getUserType())) {
            throw new ServiceException(403, "权限不足，只有管理员可以管理绘本页面");
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建绘本页面")
    @PreAuthenticated
    public CommonResult<Long> createBookPage(@Valid @RequestBody BookPageCreateReqVO createReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("创建绘本页面，绘本ID: {}, 页码: {}", createReqVO.getBookId(), createReqVO.getPageNumber());

        Long pageId = adminBookPageService.createBookPage(createReqVO);

        log.info("绘本页面创建成功，ID: {}", pageId);
        return success(pageId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新绘本页面")
    @PreAuthenticated
    public CommonResult<Boolean> updateBookPage(@Valid @RequestBody BookPageUpdateReqVO updateReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("更新绘本页面，ID: {}, 页码: {}", updateReqVO.getId(), updateReqVO.getPageNumber());

        adminBookPageService.updateBookPage(updateReqVO);

        log.info("绘本页面更新成功，ID: {}", updateReqVO.getId());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除绘本页面")
    @PreAuthenticated
    public CommonResult<Boolean> deleteBookPage(@RequestParam("id") Long id) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("删除绘本页面，ID: {}", id);

        adminBookPageService.deleteBookPage(id);

        log.info("绘本页面删除成功，ID: {}", id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得绘本页面")
    @Parameter(name = "id", description = "页面编号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<BookPageAdminRespVO> getBookPage(@RequestParam("id") Long id) {
        // 检查管理员权限
        checkAdminPermission();

        BookPageDO page = adminBookPageService.getBookPage(id);
        BookPageAdminRespVO result = BeanUtils.toBean(page, BookPageAdminRespVO.class);

        // 转换图片和音频URL为完整URL
        if (result.getImageUrl() != null) {
            result.setImageUrl(staticResourceUrlUtils.toFullUrl(result.getImageUrl()));
        }
        if (result.getOfficialAudioUrl() != null) {
            result.setOfficialAudioUrl(staticResourceUrlUtils.toFullUrl(result.getOfficialAudioUrl()));
        }

        return success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "获得绘本页面分页")
    @PreAuthenticated
    public CommonResult<PageResult<BookPageAdminRespVO>> getBookPagePage(@Valid BookPagePageReqVO pageReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        PageResult<BookPageDO> pageResult = adminBookPageService.getBookPagePage(pageReqVO);
        PageResult<BookPageAdminRespVO> result = BeanUtils.toBean(pageResult, BookPageAdminRespVO.class, respVO -> {
            // 转换图片和音频URL为完整URL
            if (respVO.getImageUrl() != null) {
                respVO.setImageUrl(staticResourceUrlUtils.toFullUrl(respVO.getImageUrl()));
            }
            if (respVO.getOfficialAudioUrl() != null) {
                respVO.setOfficialAudioUrl(staticResourceUrlUtils.toFullUrl(respVO.getOfficialAudioUrl()));
            }
        });
        return success(result);
    }

    @GetMapping("/list-by-book")
    @Operation(summary = "根据绘本ID获取页面列表")
    @Parameter(name = "bookId", description = "绘本编号", required = true, example = "1")
    @PreAuthenticated
    public CommonResult<java.util.List<BookPageAdminRespVO>> getBookPagesByBookId(@RequestParam("bookId") Long bookId) {
        // 检查管理员权限
        checkAdminPermission();

        java.util.List<BookPageDO> pages = adminBookPageService.getBookPagesByBookId(bookId);
        java.util.List<BookPageAdminRespVO> result = BeanUtils.toBean(pages, BookPageAdminRespVO.class, respVO -> {
            // 转换图片和音频URL为完整URL
            if (respVO.getImageUrl() != null) {
                respVO.setImageUrl(staticResourceUrlUtils.toFullUrl(respVO.getImageUrl()));
            }
            if (respVO.getOfficialAudioUrl() != null) {
                respVO.setOfficialAudioUrl(staticResourceUrlUtils.toFullUrl(respVO.getOfficialAudioUrl()));
            }
        });
        return success(result);
    }

    @PostMapping("/batch-create")
    @Operation(summary = "批量创建绘本页面")
    @PreAuthenticated
    public CommonResult<java.util.List<Long>> batchCreateBookPages(@Valid @RequestBody java.util.List<BookPageCreateReqVO> createReqVOs) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("批量创建绘本页面，数量: {}", createReqVOs.size());

        java.util.List<Long> pageIds = adminBookPageService.batchCreateBookPages(createReqVOs);

        log.info("批量创建绘本页面成功，IDs: {}", pageIds);
        return success(pageIds);
    }

    @GetMapping("/next-id")
    @Operation(summary = "获取下一个绘本页面ID")
    @PreAuthenticated
    public CommonResult<Long> getNextBookPageId() {
        // 检查管理员权限
        checkAdminPermission();

        Long nextId = adminBookPageService.getNextBookPageId();
        return success(nextId);
    }

}
